package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    //http://localhost:8080/order/submit

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    //http://localhost:8080/order/page?page=1&pageSize=10&number=123&beginTime=2022-05-11%2000%3A00%3A00&endTime=2022-05-19%2023%3A59%3A59

    /**
     * 条件分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param order_time
     * @param checkout_time
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "number",defaultValue = "") String number,
            @RequestParam(value = "beginTime",defaultValue = "") LocalDateTime order_time,
            @RequestParam(value = "endTime",defaultValue = "") LocalDateTime checkout_time
            ){
        //获取用户id
        Long userId = BaseContext.getCurrentId();

        //Orders分页对象
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        //OrdersDto分页对象
        Page<OrdersDto> ordersDtoPage = new Page<>();


        //设置条件
        LambdaUpdateWrapper<Orders> ordersLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //订单号
        ordersLambdaUpdateWrapper.eq(StringUtils.hasLength(number),Orders::getNumber,number);
        //本用户姓名
        //ordersLambdaUpdateWrapper.eq(userId!=1,Orders::getUserId,userId);
        //下单时间
        ordersLambdaUpdateWrapper.eq(order_time!=null,Orders::getOrderTime,order_time);
        //结束时间
        ordersLambdaUpdateWrapper.eq(checkout_time!=null,Orders::getCheckoutTime,checkout_time);
        Page<Orders> ordersPageInfo = ordersService.page(ordersPage,ordersLambdaUpdateWrapper);

        //拷贝分页属性
        BeanUtils.copyProperties(ordersPageInfo,ordersDtoPage,"records");

        List<Orders> records = ordersPageInfo.getRecords();

        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(item,ordersDto);
            //查询用户表的用户名
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(item.getUserId() != null, User::getId, item.getUserId());
            User user = userService.getOne(userLambdaQueryWrapper);
            if (user != null) {
                if(user.getName()==null){
                    user.setName("无名氏");
                }
                ordersDto.setUserName(user.getName());
            }
            return ordersDto;

        }).collect(Collectors.toList());


        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }

    //http://localhost:8080/order

    /**
     * 修改派送状态
     * @return
     */
    @PutMapping
    public R<String> deleteStatus(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return R.success("修改成功");
    }

    //http://localhost:8080/order/userPage?page=1&pageSize=1
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
       /* //获取用户id
        Long userId = BaseContext.getCurrentId();
        //订单表条件按用户id
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        //封装订单表分页对象
        Page<Orders> ordersPage = new Page<>(page,pageSize);

        //查询分页
        Page<Orders> ordersPageInfp = ordersService.page(ordersPage,ordersLambdaQueryWrapper);
        //封装OrderDetailDto分页对象
        Page<OrderDetailDto> orderDetailDtoPage = new Page<>();
        //拷贝分页对象
        BeanUtils.copyProperties(ordersPageInfp,orderDetailDtoPage,"records");

        //操作ordersList封装List<OrderDetailDto>
        List<Orders> ordersList = ordersPage.getRecords();

        OrderDetailDto orderDetailDto = new OrderDetailDto();
        for (Orders orders : ordersList) {
            //获取下单时间
            orderDetailDto.setOrderTime(orders.getOrderTime());
            //获取状态
            orderDetailDto.setStatus(orders.getStatus());

            Long ordersId = orders.getId();
            //条件
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,ordersId);

            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDetailDto.setOrderDetails(orderDetails);

            AtomicInteger sumNumber = new AtomicInteger(0);
            AtomicInteger amount = new AtomicInteger(0);
            //设置菜品总数和实收金额
            for (OrderDetail orderDetail : orderDetails) {
                sumNumber.addAndGet(orderDetail.getNumber());
                amount.addAndGet(orderDetail.getAmount().intValue());
            }
            //菜品总数
            orderDetailDto.setSumNumber(sumNumber.intValue());
            //实收金额
            orderDetailDto.setAmount(new BigDecimal(amount.intValue()));
        }
        */





       /* LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        List<Orders> ordersList = ordersService.list(ordersLambdaQueryWrapper);

        for (Orders orders : ordersList) {
            OrderDetailDto orderDetailDto = new OrderDetailDto();
            Long orderId = orders.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
        }

        OrderDetailDto orderDetailDto = new OrderDetailDto();*/


        //return R.success(orderDetailDtoPage);


        Long userId = BaseContext.getCurrentId();
        //订单表条件按用户id
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        //封装订单表分页对象
        Page<Orders> ordersPage = new Page<>(page,pageSize);

        //查询分页
        Page<Orders> ordersPageInfp = ordersService.page(ordersPage,ordersLambdaQueryWrapper);
        //封装OrderDetailDto分页对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //拷贝分页对象
        BeanUtils.copyProperties(ordersPageInfp,ordersDtoPage,"records");

        //操作ordersList封装List<OrderDetailDto>
        List<Orders> ordersList = ordersPage.getRecords();

        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(item,ordersDto);

            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(item.getId() != null, OrderDetail::getOrderId, item.getId());

            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);

            ordersDto.setOrderDetails(orderDetailList);

            return ordersDto;

        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);

        return R.success(ordersDtoPage);
    }



    //http://localhost:8080/order/again
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        ordersService.again(orders);
        return R.success("添加成功");
    }

}
